package com.charactereducation.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.charactereducation.tools.myRunTime.MyRunTimeExcption;
import com.charactereducation.tools.result.ResultObj;
import com.charactereducation.tools.result.ReturnCode;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Baggio on 2019-2-15.
 */

@ControllerAdvice
public class ExceptionController {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionController.class);

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public String errorHandler(Exception ex) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ReturnCode.FAIL.getCode());
        resultObj.setMsg(ex.getMessage());
        return resultObj.toJson();
    }

    @ResponseBody
    @ExceptionHandler(value = FeignException.class)
    public String feignExceptionHandler(FeignException ex) throws Exception {
        ex.printStackTrace();

        String content = StringUtils.substringBetween(ex.getMessage(), "{", "}");
        logger.info(ex.getMessage() + "===================>>>>>" + content);
        JSONObject jsonObject = JSON.parseObject("{" + content + "}");
        String message = jsonObject.getString("message");
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ReturnCode.FAIL.getCode());
        resultObj.setMsg(message);
        return resultObj.toJson();
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyRunTimeExcption.class)
    public String myErrorHandler(MyRunTimeExcption ex) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ex.getErroCode());
        resultObj.setMsg(ex.getMessage());
        return resultObj.toJson();
    }


}
